﻿using System;
using System.Collections.Generic;
using Microsoft.Phone.Tasks;
using Serene.Storage;
using System.Windows;
using System.Threading;

namespace Serene
{
    public class SereneManager : ISereneManager, IDisposable
    {
        private readonly IEnumerable<ICriteria> _criteria;
        private readonly Status _status;
        readonly SereneStorage _storage = new SereneStorage();

        public SereneManager(IEnumerable<ICriteria> criteria)
        {
            _criteria = criteria;

            //Load status
            _status = _storage.LoadStatus();
            _storage.LoadCriteriaSettings();
        }

        public IReadonlyStatus RunCriteria()
        {
            _storage.LoadCriteriaSettings();
            var meetsAll = true;
            foreach(var c in _criteria)
            {
                var result = c.MeetsCriteria(_status, _storage.CriteriaStorage);
                if(c.Type == CriteriaType.And && result == false)
                {
                    meetsAll = false;
                }
                else if(c.Type == CriteriaType.Single && result)
                {
                    meetsAll = true;
                    break;
                }
            }

            _storage.SaveCriteria();

            _status.MeetsCriteria = meetsAll;
            _storage.SaveStatus(_status);
            return _status;
        }

        public void RedirectToMarketPlaceIfRequired(string prompt, string promptTitle, DateTime remindAgainIn)
        {
            if(_status.MeetsCriteria == false || _status.HasRated ||
                (_status.RemindAgain.HasValue && _status.RemindAgain.Value >= DateTime.Now))
                return;

            ThreadPool.QueueUserWorkItem(_ => 
                Deployment.Current.Dispatcher.BeginInvoke(() =>
                    {
                        if(MessageBox.Show(prompt, promptTitle, MessageBoxButton.OKCancel) == MessageBoxResult.OK)
                        {
                            RedirectToMarketPlace();
                        }
                        else
                        {
                            RemindAgainLater(remindAgainIn);
                        }
                    }));
        }

        public void RedirectToMarketPlace()
        {
            _status.HasRated = true;
            _storage.SaveStatus(_status);

            var marketPlaceTask = new MarketplaceReviewTask();
            marketPlaceTask.Show();
        }

        public void RemindAgainLater(DateTime when)
        {
            _status.RemindAgain = when;
            _status.TimesReminded++;
            _storage.SaveStatus(_status);
        }

        public void Dispose()
        {
            _storage.Dispose();
        }
    }
}
